class Game {
  constructor(canvas, fps = 60) {
    this.fps = fps
    this.canvas = canvas
    this.context = canvas.getContext('2d')
    this.keydowns = {}
    this.actions = {}
    this.timer = null
    this.over = false
    this._scene = null
    this.setup()
  }

  static new(...args) {
    return new this(...args)
  }

  runLoop() {
    /* clear */
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)

    this.executeAction()


    this.update()

    this.draw()
  }

  replaceScene(scene) {
    this._scene = scene
  }

  update() {
    this._scene.update()
  }

  draw() {
    this._scene.draw()
  }

  registerAction(key, callback) {
    this.actions[key] = callback
  }

  executeAction() {
    let keys = Object.keys(this.actions)
    for (let i = 0; i < keys.length; i++) {
      let k = keys[i]
      let keyStatus = this.keydowns[k]
      if (keyStatus === 'down') {
        this.actions[k](keyStatus)
      } else if (keyStatus === 'up') {
        this.actions[k](keyStatus)
        this.keydowns[k] = null
      }
    }
  }

  setup() {

    this.timer = setInterval(() => {
      this.runLoop()
    }, 1000 / this.fps)

    window.addEventListener('keydown', (event) => {
      this.keydowns[event.key] = 'down'
    })

    window.addEventListener('keyup', (event) => {
      this.keydowns[event.key] = 'up'
    })

  }

  onGameOver() {
    console.log('onGameOver');
  }
}